<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation\providers;

/**
 * 谷歌翻译提供商
 */
class GoogleTranslateProvider extends AbstractTranslateProvider
{
    protected function validateConfig()
    {
        if (!$this->hasConfig('api_key')) {
            throw new \Exception('谷歌翻译需要配置 api_key');
        }
    }

    public function translate($text, $targetLanguage, $sourceLanguage = 'zh_CN')
    {
        $text = $this->cleanText($text);
        if (empty($text)) {
            return '';
        }

        $target = $this->convertLanguageCode($targetLanguage);
        $source = $this->convertLanguageCode($sourceLanguage);

        $data = [
            'q'      => $text,
            'target' => $target,
            'source' => $source,
            'format' => 'text',
            'key'    => $this->getConfig('api_key'),
        ];

        try {
            $response = $this->sendRequest($this->getConfig('endpoint'), $data, 'POST');
            $result   = json_decode($response, true);

            if (!$result || isset($result['error'])) {
                $errorMsg = $result['error']['message'] ?? '翻译请求失败';
                throw new \Exception($errorMsg);
            }

            if (!isset($result['data']['translations'][0]['translatedText'])) {
                throw new \Exception('翻译结果格式错误');
            }

            $translatedText = $result['data']['translations'][0]['translatedText'];
            $this->logTranslation($text, $translatedText, $targetLanguage, $sourceLanguage, 'google');

            return $translatedText;

        } catch (\Exception $e) {
            $this->handleTranslationError($e->getMessage(), 'google');
        }
    }

    private function convertLanguageCode($languageCode)
    {
        $languageMap = [
            'zh_CN' => 'zh-cn',
            'en_US' => 'en',
            'ja_JP' => 'ja',
            'ko_KR' => 'ko',
            'fr_FR' => 'fr',
            'de_DE' => 'de',
            'es_ES' => 'es',
            'pt_PT' => 'pt',
            'ru_RU' => 'ru',
            'ar_SA' => 'ar',
        ];

        return $languageMap[$languageCode] ?? 'auto';
    }
}
